<?php


namespace app\api\controller;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use app\api\model\ExpressModel;
use app\api\model\FragmentModel;
use app\api\model\GameModel;
use app\api\validate\LoginValidate;
use Lianlu\Lianlu\Clients\SmsSend;
use Lianlu\Lianlu\Common\Credential;
use Lianlu\Lianlu\models\Sms;
use library\File;
use think\Exception;
use think\facade\Cache;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Pub extends ApiBase
{

    /**
     * 上传图片
     *
     */
    public function uploadImg(){

        $params = input();
        $file = $this->request->file('file');
        $name = $file->getInfo()['name'];
        $index = strripos($file->getInfo()['name'],'.');
        $suffix = substr($file->getInfo()['name'],$index+1);
        $imgs = ['bmp','jpg','png','jpeg','tif','gif','pcx','tga','exif','fpx','svg','psd','webp','avif','apng','WMF','raw'];
        $vodeos = ['mp4','3gp','wmv','mov','m4v','rm','rmvb','asf','asx'];
        if(in_array($suffix,$imgs)){
            $folder = 'IMAGES/'.date('Y-m-d',time()).'/';
        }elseif(in_array($suffix,$vodeos)){

            $folder = 'IVIDEOS/'.date('Y-m-d',time()).'/';
        }else{

            $folder = 'FILES/';
        }
        $info = File::instance('oss')->save(date('Ymd',time()) .'/'.$folder.$name, file_get_contents($file->getRealPath()));
        if (is_array($info) && isset($info['url'])) {

            $this->successful('上传成功',$info['url']);
        } else {

            $this->fail('文件处理失败，请稍候再试！');
        }

    }

    /**
     *
     * 碎片管理信息
     */
    public function info(){

        $data = FragmentModel::info(input('id'));
        $this->successful('查询成功',$data);
    }

    /**
     *
     * 游戏列表
     */
    public function gameList(){

        $data = GameModel::gameList();
        $this->successful('查询成功',$data);
    }


    /**
     *
     * 发送验证码
     */
    public function sendCode(LoginValidate $request){
        $params = $this->request->post();
        if (!$request->scene('sendCode')->check($params)){

            $this->fail($request->getError());
        }
        $code = mt_rand(100000,999999);
        $templateParam = ['code' => $code]; // 验证码
        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $params['phone'],
            "signName" => '码谷重庆信息科技有限公司',
            "templateCode" => "SMS_468670029",
            "templateParam" => json_encode($templateParam)
        ]);
        $runtime = new RuntimeOptions([]);
        //try {
        // 复制代码运行请自行打印 API 的返回值
        $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        if ($res->body->code == "OK"){

            Cache::set($params['phone'],$code,180);
            $this->successful('发送验证码成功',$code);
        }else{

            $this->fail($res->body->message);
        }
        //}
//        catch (Exception $error) {
//            if (!($error instanceof TeaError)) {
//                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
//            }
//            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
//            // 错误 message
////            var_dump($error->message);
////            // 诊断地址
////            var_dump($error->data["Recommend"]);
////            Utils::assertAsString($error->message);
//           // $this->fail($error->getMessage());
//        }
    }


    public function createClient(){
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => 'LTAI5tFWUhmS17x4mr7dRiWQ',
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => 'e1AlwaHSTdkAZYGpC1wVAmU7ZNeVUP'
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }


}